//
// Created by Zain on 2016/9/9.
//

#include "FileOutputStream.h"

using namespace ZainTL;
using namespace std;

FileOutputStream::FileOutputStream(const char *path) : OutputStream(path) {
    mOStream = new ofstream(path, fstream::out | fstream::binary);
}

FileOutputStream::~FileOutputStream() {
    if (mOStream) {
        ((ofstream *) mOStream)->close();
        delete (mOStream);
    }
}

void FileOutputStream::write(const char *buffer, std::streamsize bufferSize) {
    ofstream *fileOutputStream = (ofstream *) mOStream;
    fileOutputStream->write(buffer, bufferSize);
}

void FileOutputStream::writeChar(char v) {
    char buffer[1]{v};
    ofstream *fileOutputStream = (ofstream *) mOStream;
    fileOutputStream->write(buffer, 1);
}

void FileOutputStream::writeShort(uint16_t v) {
    char buffer[2];
    uintToByteArray(v, buffer, 2);
    ofstream *fileOutputStream = (ofstream *) mOStream;
    fileOutputStream->write(buffer, 2);
}

void FileOutputStream::writeString(std::string v) {
    ofstream *fileOutputStream = (ofstream *) mOStream;
    fileOutputStream->write(v.c_str(), v.size() + 1);//string[string.size()] is guaranteed to be '\0'.
}

void FileOutputStream::writeLong(uint64_t v) {
    char buffer[8];
    uintToByteArray(v, buffer, 8);
    ofstream *fileOutputStream = (ofstream *) mOStream;
    fileOutputStream->write(buffer, 8);
}
